<?php

namespace app\common\utils;

use think\facade\Log;
use think\helper\Str;
use think\Response;
use think\exception\HttpResponseException;

/**
 * 工具类
 */
class CommonUtil
{
    public static function log($msg, $content = [], $level = 'info')
    {
        if (is_string($content)) {
            $arr = json_decode($content, true);
            if (is_array($arr)) {
                $content = $arr;
            }
        }
        $data = [
            'msg' => $msg,
            'content' => $content,
            'track_id' => TRACK_ID,
            'ip' => request()->ip(),
        ];

        Log::record(json_encode($data, JSON_UNESCAPED_UNICODE), $level);
    }

    /**
     *  错误
     * @param $code
     * @param $msg
     */
    public static function throwException($code = 0, $msg = '')
    {
        self::response($code, $msg);
    }

    /**
     * 输出
     * @param int $code
     * @param string $msg
     * @param string $data
     */
    public static function response($code = 0, $msg = '', $data = '')
    {
        if ($data === '') {
            $data = new \stdClass();
        }
        $outData = [
            'code' => $code,
            'msg' => $msg,
            'time' => time(),
            'data' => $data,
        ];
        $response = Response::create($outData, 'json');
        //CommonUtil::log('返回参数', $outData);
        throw new HttpResponseException($response);
    }

    /**
     * 分页处理
     * @param $page
     * @param $pageSize
     * @return array
     */
    public static function getPage($page, $pageSize)
    {
        $page = $page < 1 ? 1 : $page;
        $pageSize = $pageSize > 20 || empty($pageSize) ? 20 : $pageSize;
        $offset = ($page - 1) * $pageSize;

        return [$page, $pageSize, $offset];
    }

    /**
     * 分页输出
     * @param $data
     * @param int $page
     * @param int $pageSize
     * @param int $total
     * @return array
     */
    public static function outPage($data, $page = 1, $pageSize = 10, $total = 0)
    {
        return [
            'items' => $data,
            'page' => $page,
            'pageSize' => $pageSize,
            'total' => $total
        ];
    }

    /**
     * 字符串转图片
     * @param $str
     * @param string $delimiter
     * @return array
     */
    public static function strToArr($str, $delimiter = '|')
    {
        if (empty($str)) {
            return [];
        }
        if (is_array($str)) {
            return $str;
        }
        $arr = explode($delimiter, $str);
        return is_array($arr) ? $arr : [];
    }


    /**
     * 移除域名信息
     * @param string $url
     * @return mixed|string
     */
    public static function rmImageDomain(string $url)
    {
        $domain = parse_url($url);
        if (empty($domain)) {
            return '';
        }
        $res = '';
        if (isset($domain['path'])) {
            $res = $domain['path'];
        }
        if (isset($domain['query'])) {
            $res .= '?' . $domain['query'];
        }
        return $res;
    }

    /**
     * 驼峰命名转换下划线命名
     * @param array $userData
     * @param string $delimiter
     * @return array
     */
    public static function camelToUnderLine(array $userData)
    {
        if (empty($userData)) {
            return [];
        }
        $newData = [];
        foreach ($userData as $k => $v) {
            $k = Str::snake($k, '_');
            $newData[$k] = $v;
        }
        return $newData;
    }

    public static function getInviteCode($userId)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $num = strlen($chars);
        $str = '';
        while ($userId > 0) {
            $mod = $userId % $num;
            $userId = ($userId - $mod) / $num;
            $str = $chars[$mod] . $str;
        }

        $cd = self::createNonceStr(6 - strlen($str));

        // 不足用随机字符串补充，10表示邀请码邀请10位
        return str_pad($str, 6, $cd, STR_PAD_LEFT);
    }

    public static function createNonceStr($length = 16)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    public static function substrRealName($user_name){
        $strlen     = mb_strlen($user_name, 'utf-8');
        $firstStr     = mb_substr($user_name, 0, 1, 'utf-8');
        $lastStr     = mb_substr($user_name, -1, 1, 'utf-8');
        return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
    }
}
